package com.ncloud.resman.service.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.excel.ExcelUtil;
import com.ncloud.common.utils.excel.TemplateFileUtil;
import com.ncloud.resman.entity.Cabinet;
import com.ncloud.resman.entity.CabinetExcel;
import com.ncloud.resman.entity.CabinetUse;
import com.ncloud.resman.mapper.CabinetMapper;
import com.ncloud.resman.mapper.CabinetUseMapper;
import com.ncloud.resman.mapper.SequenceMapper;
import com.ncloud.resman.service.CabinetService;
@Service
public class CabinetServiceImpl implements CabinetService{
	@Resource
	private CabinetMapper cabinetMapper;
	@Resource
	private CabinetUseMapper cabinetUseMapper;
	@Resource
	private SequenceMapper sequenceMapper;

	@Override
	public JSONArray getCabinetInfo(JSONObject json) {
		Integer areaId = json.getInteger("areaId");
		Integer countryId = json.getInteger("countryId");
		Integer provinceId = json.getInteger("provinceId");
		Integer cityId = json.getInteger("cityId");
		Integer roomId = json.getInteger("roomId");
		Integer placeNum = json.getInteger("placeNum");
		Integer state = json.getInteger("state");
		List<JSONObject> cabinets = cabinetMapper.getCabinetInfo(areaId, countryId, provinceId, cityId, roomId, placeNum, state);
		JSONArray results=JSON.parseArray(JSON.toJSONString(cabinets));
		return results;
	}

	@Override
	public int insertCabinet(Cabinet cabinet) {
		List<JSONObject> temps = cabinetMapper.getCabinetByCode(cabinet.getRoomId(), cabinet.getCabinetCode());
		if(temps!=null && temps.size()>0){
			throw new UserException(4003,"机柜名称重复,机房:"+cabinet.getRoomName()+",机柜:"+cabinet.getCabinetCode());  
		}
		Long cabinetId = sequenceMapper.getSequence("cabinet_id").longValue();
		cabinet.setCabinetId(cabinetId);
		int result= cabinetMapper.insertCabinet(cabinet);
		Integer placeNum = cabinet.getPlaceNum();
		for(int i=1;i<=placeNum;i++)
		{
			CabinetUse cu=new CabinetUse();
			cu.setCabinetId(cabinetId);
			//cu.setSnNum("");
			cu.setUseNum(i);
			cu.setState(0);
			cabinetUseMapper.insertCabinetUse(cu);
		}
		return result;
	}

	@Override
	public int updateCabinet(Cabinet cabinet) {
		List<JSONObject> temps = cabinetMapper.getCabinetByCode(cabinet.getRoomId(), cabinet.getCabinetCode());
		if(temps!=null && temps.size()>1){
			throw new UserException(4003,"机柜名称重复,机房:"+cabinet.getRoomName()+",机柜:"+cabinet.getCabinetCode());  
		}
		return cabinetMapper.updateCabinet(cabinet);
	}

	@Override
	public int deleteCabinet(Long cabinetId) {
		cabinetUseMapper.deleteCabinetUse(cabinetId);
		return cabinetMapper.deleteCabinet(cabinetId);
	}
	@Override
	public int importCabinet(Long userId, InputStream inputStream) {
		List<Object> cabinets = ExcelUtil.getInstance().readExcel2ObjsByInputStream(inputStream, Cabinet.class);
		if(cabinets==null||cabinets.size()==0){
			return 0;
		}
		for(int i=0;i<cabinets.size();i++){
			Cabinet cabinet = (Cabinet)cabinets.get(i);
			Long cabinetId = sequenceMapper.getSequence("cabinet_id").longValue();
			cabinet.setCabinetId(cabinetId);
			if(cabinet.getRoomId()==0){
				Integer roomId=0;
				List<JSONObject> rooms = cabinetMapper.getRoomIdByName(cabinet.getRoomName());
				if(rooms==null || rooms.size()==0){
					throw new UserException(4001,"机房不存在");  
				}else if(rooms.size()>1){
					throw new UserException(4002,"存在多个名字相同的机房");  
				}
				roomId=rooms.get(0).getInteger("roomId");
				cabinet.setRoomId(roomId);
			}else{
				List<JSONObject> rooms = cabinetMapper.getRoomById(cabinet.getRoomId());
				if(rooms==null || rooms.size()==0){
					throw new UserException(4001,"机房不存在");  
				}
			}
			List<JSONObject> temps = cabinetMapper.getCabinetByCode(cabinet.getRoomId(), cabinet.getCabinetCode());
			if(temps!=null && temps.size()>0){
				throw new UserException(4003,"机柜名称重复,机房:"+cabinet.getRoomName()+",机柜:"+cabinet.getCabinetCode());  
			}
			cabinet.setCreateUser(userId);
			cabinet.setCreateDate(new Date());
			cabinet.setRemarks("批量导入");
			cabinetMapper.insertCabinet(cabinet);
			Integer placeNum = cabinet.getPlaceNum();
			for(int j=1;j<=placeNum;j++)
			{
				CabinetUse cu=new CabinetUse();
				cu.setCabinetId(cabinetId);
				cu.setUseNum(j);
				cu.setState(0);
				cabinetUseMapper.insertCabinetUse(cu);
			}
		}
		return cabinets.size();
	}

	@Override
	public int exportCabinet(JSONObject json,HttpServletResponse response) throws IOException {
		List<CabinetExcel> cabinets = cabinetMapper.getCabinetInfoExport();
		OutputStream os = null;
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=cabinets.xls");
        os = response.getOutputStream();
		ExcelUtil.getInstance().exportObj2Excel(os, cabinets, CabinetExcel.class);
		return cabinets.size();
		
	}
	@Override
	public Cabinet getRommIdByCabinetCode(String cabinetCaode) {
		return cabinetMapper.getRommIdByCabinetCode(cabinetCaode);
	}


	@Override
	public int exportTemplate(HttpServletResponse response) throws IOException {
		OutputStream os = null;
		response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=template.xls");
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        try {
          os = response.getOutputStream();
          bis = new BufferedInputStream(TemplateFileUtil.getTemplates("cabinet-infos-template.xls"));
          int i = bis.read(buff);
          while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          if (bis != null) {
            try {
              bis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
		return 1;
	}
}
